package com.imooc.flink.mysql;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * @author: Chen Yixing
 * @since: 2023/10/16 15:08:49
 * @description:
 */
public class MysqlApplication {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //自定义source
        DataStreamSource<Tuple2<Long, String>> source = env.addSource(new MysqlSource());

        //创建table流
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        Table testTable = tableEnv.fromDataStream(source);
        //创建临时表 test
        tableEnv.createTemporaryView("test", testTable);

        //sql语句直接操作临时表test
        Table resultTable = tableEnv.sqlQuery("select * from test");
        tableEnv.toRetractStream(resultTable, Row.class).filter(x -> x.f0)
                .map((MapFunction<Tuple2<Boolean, Row>, Row>) tuple2 -> tuple2.f1)
                //自定义sink
                .addSink(new MysqlSink());

        env.execute();
    }
}
